Skip to content

Method: addNamedQuery(String, String)

1: /*
2: * JOPA
3: * Copyright (C) 2024 Czech Technical University in Prague
4: *
5: * This library is free software; you can redistribute it and/or
6: * modify it under the terms of the GNU Lesser General Public
7: * License as published by the Free Software Foundation; either
8: * version 3.0 of the License, or (at your option) any later version.
9: *
10: * This library is distributed in the hope that it will be useful,
11: * but WITHOUT ANY WARRANTY; without even the implied warranty of
12: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13: * Lesser General Public License for more details.
14: *
15: * You should have received a copy of the GNU Lesser General Public
16: * License along with this library.
17: */
18: package cz.cvut.kbss.jopa.query;
19:
20: import java.util.HashMap;
21: import java.util.Map;
22: import java.util.Objects;
23:
24: /**
25: * Manages named queries in the persistence unit.
26: */
27: public class NamedQueryManager {
28:
29: private final Map<String, String> queryMap = new HashMap<>();
30:
31: /**
32: * Adds a named query mapping.
33: *
34: * @param name Named of the query
35: * @param query Query string
36: * @throws IllegalArgumentException If there already exists a mapping for the specified name
37: */
38: public void addNamedQuery(String name, String query) {
39: Objects.requireNonNull(name);
40: Objects.requireNonNull(query);
41:• if (queryMap.containsKey(name)) {
42: throw new IllegalArgumentException("Query with name " + name + " already exists in this persistence unit.");
43: }
44: queryMap.put(name, query);
45: }
46:
47: /**
48: * Gets a query mapped by the specified name.
49: *
50: * @param name Query name
51: * @return Query string
52: * @throws IllegalArgumentException If a query has not been defined with the given name
53: */
54: public String getQuery(String name) {
55: if (!queryMap.containsKey(name)) {
56: throw new IllegalArgumentException("Query with name " + name + " was not found in this persistence unit.");
57: }
58: return queryMap.get(name);
59: }
60: }